package uk.co.wroedevelopments.semanticworkbench.actions;

import java.util.Iterator;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.neo4j.api.core.NeoService;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.Transaction;
import org.neo4j.util.index.LuceneIndexService;
import org.xtext.example.myDsl.Concept;
import org.xtext.example.myDsl.DefC;
import org.xtext.example.myDsl.NewSub;
import org.xtext.example.myDsl.Ontology;

import uk.co.wroedevelopments.semanticworkbench.store.Connection;
import uk.co.wroedevelopments.semanticworkbench.store.SemanticRelationshipType;

public class ModelVisitor {

	private NeoService connection;
	private LuceneIndexService index;

	public ModelVisitor() {
		this.connection = Connection.getService();
		this.index = Connection.getIndexService();
	}

	public void visit(Ontology object, ModelSwitch sw) {
		System.out.println("Ontology");
		Transaction tx = connection.beginTx();
		try {
			for (Iterator<EObject> iterator = object.eContents().iterator(); iterator
					.hasNext();) {
				EObject member = iterator.next();
				sw.doSwitch(member);
			}
			tx.success();
		}
		catch (Exception e) {
			e.printStackTrace();
		
		} finally {
			tx.finish();
		}
	}

	public void visit(NewSub object, ModelSwitch sw) {
		System.out.println("NewSub");
		Concept parent = object.getParentConcept();
		Node parentNode = index.getSingleNode("name", parent.getName());
		System.out.println("\t parent= " + parent.getName());
		for (Concept c : object.getNewSubs()) {
			System.out.println("\t\t child= " + c.getName());
			Node nde = connection.createNode();
			nde.setProperty("name", c.getName());
			index.index(nde, "name", c.getName());
			nde.createRelationshipTo(parentNode, SemanticRelationshipType.SUBSUMPTION);
		}
	}

	public void visit(DefC object, ModelSwitch sw) {
		System.out.println("Def Concept");
		for (Concept c : object.getConcepts()) {
			System.out.println(c.getName());
			Node nde = connection.createNode();
			nde.setProperty("name", c.getName());
			index.index(nde, "name", c.getName());
		}
	}

}
